package com.sk.cardeal.act.home.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.dyhdyh.widget.loading.dialog.LoadingDialog;
import com.sk.cardeal.R;
import com.sk.cardeal.base.BaseActivity;
import com.sk.cardeal.callback.HandleDataCallBack;
import com.sk.cardeal.entity.FixType;
import com.sk.cardeal.entity.FixTypeList;
import com.sk.cardeal.entity.NewIOrderEntity;
import com.sk.cardeal.utils.AppApi;
import com.sk.cardeal.utils.MyUtils;
import com.sk.cardeal.utils.SnackUtils;
import com.sk.cardeal.view.LineMenuView;
import com.sk.cardeal.view.TitleView;

import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

import static com.sk.cardeal.common.Constants.CHOOSE_TYPE;

/**
 * Created by sk on 2017/12/25.
 */

@RuntimePermissions
public class NewOrderActivity extends BaseActivity implements HandleDataCallBack {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.car_num)
    EditText carNum;
    @BindView(R.id.pep_name)
    EditText pepName;
    @BindView(R.id.tv_phone)
    EditText tvPhone;
    @BindView(R.id.phone_icon)
    ImageView phoneIcon;
    @BindView(R.id.oder_time)
    LineMenuView oderTime;
    @BindView(R.id.fix_type)
    LineMenuView fixType;
    @BindView(R.id.add)
    TextView add;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ed_note)
    EditText edNote;

    private NewIOrderEntity newIOrderEntity;
    private LoadingDialog loadingDialog;

    @Override
    protected int getContentView() {
        return R.layout.activity_new_order;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleView.setMyCallBack(this);
        loadingDialog = MyUtils.getLoadingDialog(mContext, false);
        newIOrderEntity = new NewIOrderEntity();
        newIOrderEntity.setShopId(MyUtils.getUser(mContext).getCompanyId());
    }

    @Override
    public void clickTitle(int i) {
        super.clickTitle(i);
        switch (i) {
            case 1:
                finish();
                break;
            case 2:
                break;
            case 3:
                break;
        }
    }


    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void startCall() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + tvPhone.getText().toString());
        intent.setData(data);
        startActivity(intent);
    }

    // 向用户说明为什么需要这些权限（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showRationaleForPhone(final PermissionRequest request) {
        new AlertDialog.Builder(mContext)
                .setMessage("源圈需要使用您的电话！")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }

    // 用户拒绝授权回调（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showDeniedForPhone() {
        SnackUtils.showError(mRootView, "您拒绝了电话权限！");
    }


    // 用户勾选了“不再提醒”时调用（可选）
    @NeedsPermission({Manifest.permission.CALL_PHONE})
    void showNeverAskForPhone() {
        new AlertDialog.Builder(mContext)
                .setMessage("您已禁止app使用您的电话,请到设置中开启。")
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
                            // 进入设置系统应用权限界面
                            Intent intent = new Intent(Settings.ACTION_SETTINGS);
                            startActivity(intent);
                            return;
                        }
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .show();
    }


    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        NewOrderActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    @OnClick({R.id.phone_icon, R.id.oder_time, R.id.fix_type, R.id.add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.phone_icon:
                NewOrderActivityPermissionsDispatcher.startCallWithPermissionCheck(NewOrderActivity.this);
                break;
            case R.id.oder_time:
                DatePickDialog dialog = new DatePickDialog(this);
                //设置上下年分限制
                dialog.setYearLimt(5);
                //设置标题
                dialog.setTitle("选择进场日期");
                //设置类型
                dialog.setType(DateType.TYPE_ALL);
                //设置消息体的显示格式，日期格式
                dialog.setMessageFormat("yyyy-MM-dd HH:mm");
                //设置选择回调
                dialog.setOnChangeLisener(null);
                //设置点击确定按钮回调
                dialog.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        oderTime.setHint(MyUtils.stampToDate(date.getTime()));
                        newIOrderEntity.setConventionTime(MyUtils.stampToDate(date.getTime()));
                        oderTime.setHintColor(Color.parseColor("#232323"));
                    }
                });
                dialog.show();
                break;
            case R.id.fix_type:
                loadingDialog.show();
                AppApi.getFixType(NewOrderActivity.this, 7, NewOrderActivity.this);

                break;
            case R.id.add:

                if (TextUtils.isEmpty(carNum.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入需要预约的车牌号");
                    return;
                }

                if (TextUtils.isEmpty(pepName.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入需要预约人的姓名");
                    return;
                }

                if (TextUtils.isEmpty(tvPhone.getText().toString())) {
                    SnackUtils.showError(mRootView, "请输入预约人的电话");
                    return;
                }

                if (TextUtils.isEmpty(newIOrderEntity.getConventionTime())) {
                    SnackUtils.showError(mRootView, "请选择您要预约的时间");
                    return;
                }

                if (TextUtils.isEmpty(newIOrderEntity.getConventionTypeId())) {
                    SnackUtils.showError(mRootView, "请选择您要预约的维修类型");
                    return;
                }

                setData();
                loadingDialog.show();
                AppApi.addNewOrder(newIOrderEntity, NewOrderActivity.this, 8, NewOrderActivity.this);
                break;
        }
    }

    @Override
    public void handlerSuccessData(String result, int tag) {
        loadingDialog.cancelDialog();
        switch (tag) {
            case 7:
                FixTypeList fixTypeList = JSON.parseObject(result, FixTypeList.class);
                ArrayList<FixType> fixTypes = (ArrayList<FixType>) fixTypeList.getResultList();
                Intent intent = new Intent(mContext, FixTypeActivity.class);
                intent.putExtra("data", fixTypes);
                startActivityForResult(intent, CHOOSE_TYPE);
                break;
            case 8:
                loadingDialog.cancelDialog();
                Toast.makeText(mContext, "预约新增成功！", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                finish();
                break;
        }

    }

    @Override
    public void handlerFailData(String failString, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    public void handleErrorData(String error, int tag) {
        loadingDialog.cancelDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == -1) {
            switch (requestCode) {
                case CHOOSE_TYPE:
                    FixType selectType = data.getParcelableExtra("data");
                    fixType.setHint(selectType.getName());
                    fixType.setHintColor(Color.parseColor("#232323"));
                    newIOrderEntity.setConventionTypeId(selectType.getId());
                    break;
            }
        }
    }

    private void setData() {
        newIOrderEntity.setCardNumber(carNum.getText().toString());
        newIOrderEntity.setName(pepName.getText().toString());
        newIOrderEntity.setPhone(tvPhone.getText().toString());
        newIOrderEntity.setNote(edNote.getText().toString());
    }
}
